package com.tg.appcommon.transform;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RSRuntimeException;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
public class RSBlur {

    private static RSBlur sInstance;

    private RenderScript renderScript;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static RSBlur getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new RSBlur(context);
        }
        return sInstance;
    }

    private RSBlur(Context context) {
        renderScript = RenderScript.create(context);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public Bitmap blur(Bitmap bitmap, int radius) throws RSRuntimeException {

        Allocation input = null;
        Allocation output = null;
        ScriptIntrinsicBlur blur = null;
        try {
            input = Allocation.createFromBitmap(renderScript, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            output = Allocation.createTyped(renderScript, input.getType());
            blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));

            blur.setInput(input);
            blur.setRadius(radius);
            blur.forEach(output);
            output.copyTo(bitmap);
        } finally {
            if (input != null) {
                input.destroy();
            }
            if (output != null) {
                output.destroy();
            }
            if (blur != null) {
                blur.destroy();
            }
        }

        return bitmap;
    }
}
